<template>
  <div>
    <van-search
      class="search"
      v-model="searchValue"
      shape="round"
      placeholder="搜索歌曲、歌手、专辑"
      @search="onSearch"
      @input="onInput"
    />
    <router-view />
  </div>

</template>

<script>
import eventBus from '@/event-bus';
import VanSearch from 'vant/lib/search';
import * as tool from '@/utils';
import { debounce } from 'lodash';

const getSearchSuggest = debounce(function () {
  if (!this.searchValue) {
    return;
  }
  // 请求搜索建议
  eventBus.$emit('updateSearchSuggest', this.searchValue);
  this.$router.push({
    name: 'search-suggest',
    query: {
      searchValue: this.searchValue,
    },
  });
}, 1000);

export default {
  components: {
    VanSearch,
  },
  data () {
    return {
      searchValue: this.$route.query.searchValue || '',
    };
  },
  watch: {
    // 监听路由参数
    '$route.query' (newValue) {
      this.searchValue = newValue.searchValue;
    },
  },
  methods: {
    onInput (v) {
      // 判断searchValue是否为空 以跳转页面
      if (v) {
        getSearchSuggest.call(this);
      } else {
        this.$router.push('/search/search-hot');
      }
    },
    // 存储最新数据
    saveLastSearchList (newValue) {
      const lastSearchList = JSON.parse(localStorage.getItem('lastSearchList'));
      localStorage.setItem('lastSearchList', JSON.stringify(tool.unique(lastSearchList.concat(newValue))));
    },
    onSearch () {
      // 存储最新数据
      this.saveLastSearchList(this.searchValue);
      // 搜索最佳匹配
      eventBus.$emit('updateSearchMultimatch', this.searchValue);
      // 获取搜索结果
      eventBus.$emit('updateSearchList', this.searchValue);
      // 跳转至搜索结果页面
      this.$router.push({
        name: 'search-list',
        query: {
          searchValue: this.searchValue,
        },
      });
    },
  },
}
</script>

<style scoped>
.search {
  border-top: 1px solid #f5f5f5;
  border-bottom: 1px solid #f5f5f5;
}
</style>